//后台添加文章组件
import React, { useState,useEffect } from 'react';
import {marked} from 'marked'
import '../static/css/AddAritcle.css'
import { useNavigate,useParams } from "react-router-dom";

import {Row,Col,Input,Select,Button,DatePicker, message} from 'antd'
import moment from 'moment';

//后台获取数据
import axios from 'axios'
import apiUrl from '../config/apiUrl'
import servicePath from '../config/apiUrl';

const {Option} = Select
const {TextArea} =  Input

function AddAritcle(){
    let navigate = useNavigate();
    let routerParams = useParams()

    const [articleId,setArticleId] = useState(0)  // 文章的ID，如果是0说明是新增加，如果不是0，说明是修改
    const [articleTitle,setArticleTitle] = useState('')   //文章标题
    const [articleContent , setArticleContent] = useState('')  //markdown的编辑内容
    const [markdownContent, setMarkdownContent] = useState('预览内容') //html内容
    const [introducemd,setIntroducemd] = useState()            //简介的markdown内容
    const [introducehtml,setIntroducehtml] = useState('等待编辑') //简介的html内容
    const [showDate,setShowDate] = useState()   //发布日期
    const [updateDate,setUpdateDate] = useState() //修改日志的日期
    const [typeInfo ,setTypeInfo] = useState([]) // 文章类别信息
    const [selectedType,setSelectType] = useState('请选择类型') //选择的文章类别

    //设置marked
    marked.setOptions({
        renderer:new marked.Renderer(),
        gfm:true,
        pedantic:false,
        sanitize:false,
        breaks:true,
        smartLists:true,
        smartypants:false
    })

    //同步文章内容和 marked预览
    const changeContent = e=>{
        setArticleContent(e.target.value)
        let html = marked.parse(e.target.value)
        setMarkdownContent(html)
    }

    const changeIntroduce = e=>{
        setIntroducemd(e.target.value)
        let html = marked.parse(e.target.value)
        setIntroducehtml(html)
    }

    //获取文字类别信息
    const getTypeInfo = ()=>{
        axios({
            method:'get',
            url:apiUrl.type,
            withCredentials:true,

        }).then(res=>{
            if (res.data.status === -1) {
                localStorage.removeItem('openId')
                navigate('/')
            }else{
                setTypeInfo(res.data.data)
            }
        })
    }
    useEffect(()=>{
        getTypeInfo()
        //获取文章id
        console.log(routerParams)
        let tmpId = routerParams.id
        if (tmpId) {
            setArticleId(tmpId)
            editArticle(tmpId)
        }
    },[])

    //选择type
    const selectTypeHandler=(value)=>{
        console.log(value)
        setSelectType(value)
    }

    //保存文章
    const saveArticle = ()=>{
        if(selectedType  == '请选择类型'){
            message.error('必须选择文章类型')
            return false
        }else if (!articleTitle) {
            message.error('文章名称不能为空')
            return false
        }else if (!articleContent) {
            message.error('文章内容不能为空')
            return false
        }else if (!introducemd) {
            message.error('文章简介不能为空')
            return false
        }else if (!showDate) {
            message.error('发布日志不能为空')
            return false
        }
        let params = {}
        params.type_id = Number(selectedType)
        params.title = articleTitle
        params.article_content = articleContent
        params.introduce = introducemd
        console.log(showDate)
        let dateText = showDate.replace('-','/')
        params.addTime = (new Date(dateText).getTime() / 1000)

        //文章的ID，如果是0说明是新增加，如果不是0，说明是修改
        if (articleId == 0) {
            params.view_count = 0;
            axios({
                method:'post',
                url:apiUrl.addArticle,
                // headers:{'Content-Type':'application/x-www-form-urlencoded'},
                data:params,
                withCredentials:true
            }).then(res=>{
              
                if (res.data.status) {
                    // setArticleId(res.data.data.id)
                    message.success('文章保存成功！')
                }else{
                    message.error('文章保存失败！')
                }
            })
        }else{
            params.id = articleId
            axios({
                method:'post',
                url:apiUrl.updateArticle,
                data:params,
                withCredentials:true,
            }).then(res=>{
                if (res.data.status) {
                    message.success('修改文章成功')
                }else{
                    message.error('修改文章失败')
                }
            })
        }
    }

    //从文章列表跳过来的,暂存的文字修改
    const editArticle = (id)=>{
        axios(servicePath.editArticle + id,{withCredentials:true}).then(res=>{
            if (res.data.status) {
                let articleInfo = res.data.data[0]
                setArticleTitle(articleInfo.title)
                setArticleContent(articleInfo.article_content)
                let html=marked.parse(articleInfo.article_content)
                setMarkdownContent(html)
                setIntroducemd(articleInfo.introduce)
                let tmpInt = marked.parse(articleInfo.introduce)
                setIntroducehtml(tmpInt)
                
                setShowDate(moment(articleInfo.addTime,'YYYY-MM-DD'))
                setSelectType(articleInfo.typeId)
            }
        })
    }
    return(
        <div>
            <Row gutter={5}>
                <Col span={18}>
                    <Row gutter={10}>
                        <Col span={20}>
                            <Input value={articleTitle} placeholder='博客标题' size='large' onChange={e=>{setArticleTitle(e.target.value)}} />
                        </Col>
                        <Col span={4}>
                            &nbsp;
                            <Select value={selectedType}  defaultValue={selectedType} size='large' onChange={selectTypeHandler}>
                                {
                                    typeInfo.map((item,index)=>{
                                        return (<Option key={index} value={item.orderNum}>{item.typeName}</Option>)
                                    })
                                }

                            </Select>
                        </Col>
                    </Row>
                    <br />
                    <Row gutter={10}>
                        <Col span={12}>
                            <TextArea onChange={changeContent} value={articleContent} className='markdown-content' rows={33} placeholder='文章内容'  />
                        </Col>
                        <Col span={12}>
                            <div className='show-html' dangerouslySetInnerHTML={{__html:markdownContent}}></div>
                        </Col>
                    </Row>
                </Col>
                <Col span={6}>
                    <Row>
                        <Col span={24}>
                            <Button size='large'>暂存文章</Button>&nbsp;
                            <Button type="primary" size='large' onClick={saveArticle}>保存文章</Button>
                            <br/>
                        </Col>
                        <Col span={24}>
                            <br />
                            <TextArea value={introducemd} onChange={changeIntroduce} rows={4} placeholder='文章简介'/>
                            <br />
                            <br />
                            <div className='introduce-html' dangerouslySetInnerHTML={{__html:introducehtml}}>

                            </div>
                        </Col>
                        <Col span={12}>
                            <div className='date-select'>
                            <DatePicker defaultValue={showDate}  onChange={(date,dateString)=>{setShowDate(dateString)}} placeholder='发布日期' size="large" />
                            </div>
                        </Col>
                        <Col span={12}>
                            <div className='date-select'>
                                <DatePicker placeholder='修改日期' size="large" />
                            </div>
                        </Col>
                    </Row>
                </Col>
            </Row>
        </div>
    )
}

export default AddAritcle